/*
 * Created by SharpDevelop.
 * User: MyWife
 * Date: 10/10/2010
 * Time: 12:08 PM
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */

using System;
using System.Collections.Generic;
using System.Collections;
using System.Drawing;
using System.Windows.Forms;
using popLib;
using System.Diagnostics;
using System.ComponentModel;
using System.IO;


namespace MediafireDownloader
{
	/// <summary>
	/// Description of URLCatcher.
	/// </summary>
	public partial class URLCatcher : Form
	{
		public ReturnSet ResultURL = new ReturnSet( false, null, "Cancel" );
		bool DocumentCompleted = false;
		bool IsProcessPassword = false;
		string password;
		string url;
		
		Timer timeup, timer;
		public URLCatcher(){}
		
		public URLCatcher(string url, string password)
		{
			//
			// The InitializeComponent() call is required for Windows Forms designer support.
			//
			InitializeComponent();
			
			webBrowser1.ScriptErrorsSuppressed = true;			
			webBrowser1.Url = new Uri(url);
			webBrowser1.DocumentCompleted += delegate { DocumentCompleted = true; };
			this.password = password;
			this.url = url;
			
			timer = new Timer();
			timer.Interval = 1000;
			timer.Tick += delegate {
				
				try{
					WindowLib.killProcess("IEXPLORE");
				}catch{}
				
				if( !DocumentCompleted ) return;
				
				timer.Stop();				
				ReturnSet rs = GetURL();
				timer.Start();
				if( rs.Success || (!rs.Success && rs.Message == "Invalid/Deleted") ){
					timeup.Stop();
					timer.Stop();					
					ResultURL = rs;
					this.Close();
				}
				
			};
			timer.Start();
			
			timeup = new Timer();
			timeup.Interval = 60000;
			timeup.Tick += delegate { 
				timeup.Stop();
				timer.Stop();
				ResultURL = new ReturnSet( false, null, "Request Timeout" );				
				this.Close();
			};
			timeup.Start();
		}
		
		
		
		ReturnSet GetURL(){
			try{
				
				//Check for all A element to get link
				HtmlElementCollection elements = webBrowser1.Document.GetElementsByTagName("a");
				foreach( HtmlElement element in elements ){
					try{
						if( (element.InnerText.Contains("Click here to start download") ||
						     element.InnerHtml.Contains("Click here to start download")) &&
						     element.Parent.Style.ToLower().Contains( "display: block" )
						   ){
							return new ReturnSet( true, element.GetAttribute("href"), element.GetAttribute("href") );
						}
					}catch{}
				}
				
				HtmlElement passElement = webBrowser1.Document.GetElementById("pprotected");				
				if( passElement != null && passElement.Style.ToLower().Contains("display: block") && DocumentCompleted && !IsProcessPassword ){
					if( !StringLib.isValid(password) ){						
						PasswordForm form = new PasswordForm(url);
						if( form.DialogResult == DialogResult.Cancel ) new ReturnSet( false, null, "WrongPassword" );	
							
						password = form.Password;
					}
					
					HtmlElement inputPassElement = webBrowser1.Document.GetElementById("downloadp");
					inputPassElement.SetAttribute("value", password);
					inputPassElement.Focus();
												
					this.Activate();					
					this.WindowState = FormWindowState.Normal;
					APILib.SetForegroundWindow(this.Handle);					
					WindowLib.MouseClick( MouseButtons.Left, Location.X + 119, Location.Y + 92 );
					WindowLib.MouseClick( MouseButtons.Left, Location.X + 119, Location.Y + 92 );
										
					IsProcessPassword = true;
				}			
							
				//Check if error message - no longer existed
				HtmlElement msgElement = webBrowser1.Document.GetElementById("statusmessage_text");
				if( msgElement != null && msgElement.InnerHtml.Contains("The content no longer seems to be available via MediaFire"))
					return new ReturnSet( false, null, "Invalid/Deleted" );				
				
				
				//Check if error message - invalid/delete
				elements = webBrowser1.Document.GetElementsByTagName("div");
				foreach( HtmlElement element in elements ){
					try{
						if( element.InnerText.Contains("Invalid or Deleted File") ||
						     element.InnerHtml.Contains("Invalid or Deleted File")
						   ){
							return new ReturnSet( false, null, "Invalid/Deleted" );
						}
					}catch{}
				}
						 
				
				return new ReturnSet(false, null, "Unknown Error");
				
			}catch(Exception ex){
				return new ReturnSet(false, null, ex.Message );
			}
		}		
	}
}
